package com.huluobo.a2207mmonthdemo.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.a2207mmonthdemo.R;
import com.huluobo.a2207mmonthdemo.adapter.GiftAdapter;
import com.huluobo.a2207mmonthdemo.databinding.ActivityLiveBinding;
import com.huluobo.a2207mmonthdemo.pay.PayActivity;
import com.huluobo.a2207mmonthdemo.utils.ImageUtils;
import com.huluobo.base.bean.CommonBeanResult;
import com.huluobo.base.bean.GiftBeanResult;
import com.huluobo.base.bean.Money;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDbUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;

import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {

    private VideoBeanResult.VideoBean videoBean;
    private GiftAdapter giftAdapter;
    private GiftBeanResult.GiftBean giftBean;
    private Money money;

    @Override
    protected void initData() {
        vm.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(1);
                binding.liveFollowBtn.setText("已关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_black);
            }
        });
        vm.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        vm.cancelFollowSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(0);
                binding.liveFollowBtn.setText("关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
            }
        });

        vm.cancelFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败:" + s);
        });

        vm.getGiftSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftAdapter.getData().clear();
                giftAdapter.getData().addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }
        });

        vm.getGiftFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物数据失败:" + s);
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");
        binding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        binding.liveGsyPlayer.setUp(videoBean.getHeadpath(), true, "");

        ImageUtils.getInstance().loadCircleImage(this, videoBean.getHeadpath(), binding.liveUserIconIv);
        binding.liveUsernameTv.setText(videoBean.getAuthname());
        binding.liveFollowBtn.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        binding.liveFollowBtn.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_red :
                R.drawable.shape_black);
        binding.liveLikeCountTv.setText(videoBean.getLike_count() + "人喜欢");
        binding.liveFollowBtn.setOnClickListener(v -> {
            if (videoBean.getGuanzhu() == 0) {
                vm.followAuth(videoBean.getAuthname());
            } else {
                vm.cancelFollow(videoBean.getAuthname());
            }
        });

        binding.liveLikeView.addLikeImages(
                R.drawable.fav_0,
                R.drawable.fav_1,
                R.drawable.fav_2,
                R.drawable.fav_3,
                R.drawable.fav_4,
                R.drawable.fav_5
        );

        binding.liveLikeIv.setOnClickListener(v -> {
            binding.liveLikeView.addFavor();
        });

        binding.liveDanmuIv.setOnClickListener(v -> {
            binding.liveDanmuLayoutLl.setVisibility(View.VISIBLE);
        });

        binding.liveDanmuSendIv.setOnClickListener(v -> {
            sendDanmu();
        });

        binding.liveGiftIv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            vm.getGift();
        });

        binding.liveCloseTv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.GONE);
        });

        binding.liveGiftRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter();
        binding.liveGiftRv.setAdapter(giftAdapter);

        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            giftBean = giftAdapter.getData().get(position);
            ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), binding.liveGiftSelectIv);
            binding.liveGiftSelectTv.setText(giftBean.getGiftname());
        });

        binding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        binding.livePayBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, PayActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        money = AppDbUtils.getInstance().getMoneyDao().queryMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME));
        binding.liveUserMoneyTv.setText("用户余额:" + money.getMoney() + "抖币");
    }

    private void sendGift() {
        if (giftBean == null || money == null) {
            ToastUtils.showLong("请选择了礼物,或者查询余额失败");
            return;
        }

        if (money.getMoney() < giftBean.getPrice()) {
            ToastUtils.showLong("余额不足,请充值");
            return;
        }

        float newMoney = money.getMoney() - giftBean.getPrice();
        binding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");
        money.setMoney(newMoney);
        AppDbUtils.getInstance().getMoneyDao().updateMoneyInfo(money);

        ImageView giftView = new ImageView(this);
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftView.setLayoutParams(params);

        binding.liveRootCl.addView(giftView);
        ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), giftView);

        float screenWidth = binding.liveRootCl.getMeasuredWidth();
        float screenHeight = binding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translateY = ObjectAnimator.ofFloat(giftView, "translationY", screenHeight, screenHeight / 2,
                screenHeight / 5, screenHeight / 3, screenHeight / 2);
        ObjectAnimator translateX = ObjectAnimator.ofFloat(giftView, "translationX", screenWidth / 2,
                screenWidth / 5, screenWidth / 2, screenWidth / 3 * 2, screenWidth / 2);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftView, "rotation", 0, 1800);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftView, "scaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftView, "scaleY", 1, 2, 1, 3, 1, 2, 1);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(translateX, translateY, rotation, scaleY, scaleX);

        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                binding.liveRootCl.removeView(giftView);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                binding.liveGiftLayoutCl.setVisibility(View.GONE);
            }
        });
        set.start();
    }

    private void sendDanmu() {
        String danmuString = binding.liveDanmuEt.getText().toString();
        if (danmuString.isEmpty()) {
            ToastUtils.showLong("弹幕内容不能为空");
            return;
        }

        Danmaku danmaku = new Danmaku();
        danmaku.text = danmuString;
        danmaku.size = 30;
        DanmakuManager.getInstance().init(this, binding.liveDanmuView);
        DanmakuManager.getInstance().send(danmaku);

        binding.liveDanmuEt.setText("");
        binding.liveDanmuLayoutLl.setVisibility(View.GONE);
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}